<template>
  <div class="site-management">
    <!-- 顶部操作区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="addSite('add')">新增站点</el-button>
      <el-button @click="refreshData">刷新数据</el-button>
      <el-input
          v-model="searchKeyword"
          placeholder="请输入站点名称或域名搜索"
          style="width: 300px; margin-left: 20px"
          clearable
          @clear="handleSearchClear"
          @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button @click="handleSearch">
            <el-icon><search /></el-icon>
          </el-button>
        </template>
      </el-input>
    </div>

    <!-- 主表格区域 -->
    <el-table
        :data="filteredSites"
        row-key="id"
        style="width: 100%"
        border
        v-loading="loading"
    >
      <el-table-column prop="name" label="站点名称" width="150" />
      <el-table-column prop="domain" label="主域名" width="180">
        <template #default="{ row }">
          <el-tag v-if="row.sslEnabled" type="success" size="small">
            <el-icon><lock /></el-icon>
            {{ row.domain }}
          </el-tag>
          <span v-else>{{ row.domain }}</span>
        </template>
      </el-table-column>
      <el-table-column label="子域名" width="200">
        <template #default="{ row }">
          <el-tag
              v-for="(subdomain, index) in row.subDomains"
              :key="index"
              size="small"
              style="margin-right: 5px"
          >
            {{ subdomain }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="站点类型" width="120">
        <template #default="{ row }">
          {{ getSiteTypeName(row.type) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag
              :type="row.status === 'online' ? 'success' : 'danger'"
              size="small"
          >
            {{ row.status === "online" ? "在线" : "离线" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="访问量" width="120">
        <template #default="{ row }">
          <el-tooltip
              :content="`今日: ${row.todayVisits} | 昨日: ${row.yesterdayVisits}`"
          >
            <span>{{ row.totalVisits }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="响应时间" width="120">
        <template #default="{ row }">
          <el-progress
              :percentage="getResponseTimePercentage(row.avgResponseTime)"
              :format="() => `${row.avgResponseTime}ms`"
              :color="getResponseTimeColor(row.avgResponseTime)"
              :stroke-width="15"
              :show-text="true"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="showDetail(row)">详情</el-button>
          <el-button size="small" type="primary" @click="addSite('edit', row)"
          >编辑</el-button
          >
          <el-button size="small" type="danger" @click="deleteSite(row)"
          >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalSites"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
      />
    </div>

    <!-- 站点编辑/新增对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="50%"
        @close="resetForm"
    >
      <el-form
          ref="siteFormRef"
          :model="siteForm"
          :rules="siteRules"
          label-width="120px"
      >
        <el-form-item label="站点名称" prop="name">
          <el-input v-model="siteForm.name" placeholder="请输入站点名称" />
        </el-form-item>
        <el-form-item label="站点类型" prop="type">
          <el-select
              v-model="siteForm.type"
              placeholder="请选择站点类型"
              style="width: 100%"
          >
            <el-option
                v-for="type in siteTypes"
                :key="type.value"
                :label="type.label"
                :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="主域名" prop="domain">
          <el-input
              v-model="siteForm.domain"
              placeholder="请输入主域名，如 example.com"
          />
        </el-form-item>
        <el-form-item label="子域名" prop="subDomains">
          <el-tag
              v-for="(domain, index) in siteForm.subDomains"
              :key="index"
              closable
              @close="removeSubDomain(index)"
              style="margin-right: 8px"
          >
            {{ domain }}
          </el-tag>
          <el-input
              v-model="newSubDomain"
              placeholder="输入子域名后按回车添加"
              style="width: 200px"
              @keyup.enter="addSubDomain"
          />
        </el-form-item>
        <el-form-item label="启用SSL" prop="sslEnabled">
          <el-switch v-model="siteForm.sslEnabled" />
          <span style="margin-left: 10px; color: #999">
            {{ siteForm.sslEnabled ? "已启用HTTPS" : "未启用HTTPS" }}
          </span>
        </el-form-item>
        <el-form-item label="站点状态" prop="status">
          <el-radio-group v-model="siteForm.status">
            <el-radio label="online">在线</el-radio>
            <el-radio label="offline">离线</el-radio>
            <el-radio label="maintenance">维护中</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="站点描述" prop="description">
          <el-input
              v-model="siteForm.description"
              type="textarea"
              :rows="3"
              placeholder="请输入站点描述"
          />
        </el-form-item>
        <el-form-item label="权限配置" prop="roles">
          <el-transfer
              v-model="siteForm.roles"
              :data="allRoles"
              :titles="['可用角色', '已分配角色']"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSiteForm">确认</el-button>
      </template>
    </el-dialog>

    <!-- 站点详情对话框 -->
    <el-dialog v-model="detailVisible" title="站点详情" width="60%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="站点名称">{{
            currentSite.name
          }}</el-descriptions-item>
        <el-descriptions-item label="站点类型">{{
            getSiteTypeName(currentSite.type)
          }}</el-descriptions-item>
        <el-descriptions-item label="主域名">
          <el-tag v-if="currentSite.sslEnabled" type="success">
            <el-icon><lock /></el-icon>
            {{ currentSite.domain }}
          </el-tag>
          <span v-else>{{ currentSite.domain }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="站点状态">
          <el-tag :type="currentSite.status === 'online' ? 'success' : 'danger'">
            {{ currentSite.status === "online" ? "在线" : "离线" }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
            formatDate(currentSite.createTime)
          }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{
            formatDate(currentSite.updateTime)
          }}</el-descriptions-item>
        <el-descriptions-item label="子域名" :span="2">
          <el-tag
              v-for="(domain, index) in currentSite.subDomains"
              :key="index"
              style="margin-right: 8px"
          >
            {{ domain }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="站点描述" :span="2">{{
            currentSite.description
          }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">访问统计</el-divider>
      <div class="stats-container">
        <div class="stat-item">
          <div class="stat-value">{{ currentSite.totalVisits }}</div>
          <div class="stat-label">总访问量</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ currentSite.todayVisits }}</div>
          <div class="stat-label">今日访问</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ currentSite.yesterdayVisits }}</div>
          <div class="stat-label">昨日访问</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ currentSite.avgResponseTime }}ms</div>
          <div class="stat-label">平均响应</div>
        </div>
      </div>

      <el-divider content-position="left">性能指标</el-divider>
      <div class="performance-charts">
        <div class="chart-container">
          <div class="chart-title">CPU使用率</div>
          <el-progress
              :percentage="currentSite.cpuUsage"
              :color="getUsageColor(currentSite.cpuUsage)"
              :stroke-width="20"
              :text-inside="true"
          />
        </div>
        <div class="chart-container">
          <div class="chart-title">内存使用率</div>
          <el-progress
              :percentage="currentSite.memoryUsage"
              :color="getUsageColor(currentSite.memoryUsage)"
              :stroke-width="20"
              :text-inside="true"
          />
        </div>
        <div class="chart-container">
          <div class="chart-title">带宽使用</div>
          <el-progress
              :percentage="currentSite.bandwidthUsage"
              :color="getUsageColor(currentSite.bandwidthUsage)"
              :stroke-width="20"
              :text-inside="true"
          />
        </div>
      </div>

      <el-divider content-position="left">分配角色</el-divider>
      <el-table :data="getAssignedRoles(currentSite.roles)" border>
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="description" label="角色描述" />
        <el-table-column label="权限">
          <template #default="{ row }">
            <el-tag
                v-for="(perm, index) in row.permissions"
                :key="index"
                size="small"
                style="margin-right: 5px"
            >
              {{ perm }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { Search, Lock } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";

// 模拟数据 - 站点类型
const siteTypes = [
  { value: "main", label: "主站" },
  { value: "region", label: "区域站" },
  { value: "topic", label: "专题站" },
  { value: "mobile", label: "移动站" },
  { value: "minisite", label: "微站" },
];

// 模拟数据 - 所有角色
const allRoles = ref([
  {
    key: "super_admin",
    label: "超级管理员",
    permissions: ["全部权限"],
    disabled: false,
  },
  {
    key: "content_admin",
    label: "内容管理员",
    permissions: ["内容管理", "发布管理"],
    disabled: false,
  },
  {
    key: "editor",
    label: "内容编辑",
    permissions: ["内容编辑", "草稿管理"],
    disabled: false,
  },
  {
    key: "auditor",
    label: "审核员",
    permissions: ["内容审核"],
    disabled: false,
  },
  {
    key: "guest",
    label: "访客",
    permissions: ["只读"],
    disabled: false,
  },
]);

// 模拟数据 - 初始站点数据
const initialSites = ref([
  {
    id: 1,
    name: "主站",
    type: "main",
    domain: "example.com",
    subDomains: ["www.example.com", "m.example.com"],
    sslEnabled: true,
    status: "online",
    description: "公司官方网站主站",
    roles: ["super_admin", "content_admin"],
    createTime: "2023-01-01T10:00:00",
    updateTime: "2023-06-15T14:30:00",
    totalVisits: 125430,
    todayVisits: 1245,
    yesterdayVisits: 1180,
    avgResponseTime: 120,
    cpuUsage: 45,
    memoryUsage: 60,
    bandwidthUsage: 30,
  },
  {
    id: 2,
    name: "北京区域站",
    type: "region",
    domain: "bj.example.com",
    subDomains: [],
    sslEnabled: true,
    status: "online",
    description: "北京地区专属站点",
    roles: ["content_admin", "editor"],
    createTime: "2023-02-15T09:15:00",
    updateTime: "2023-06-10T16:45:00",
    totalVisits: 32450,
    todayVisits: 320,
    yesterdayVisits: 310,
    avgResponseTime: 150,
    cpuUsage: 30,
    memoryUsage: 45,
    bandwidthUsage: 20,
  },
  {
    id: 3,
    name: "产品专题站",
    type: "topic",
    domain: "product.example.com",
    subDomains: [],
    sslEnabled: false,
    status: "online",
    description: "公司产品展示专题站点",
    roles: ["editor", "auditor"],
    createTime: "2023-03-20T14:20:00",
    updateTime: "2023-06-12T11:10:00",
    totalVisits: 45670,
    todayVisits: 420,
    yesterdayVisits: 390,
    avgResponseTime: 180,
    cpuUsage: 55,
    memoryUsage: 70,
    bandwidthUsage: 45,
  },
  {
    id: 4,
    name: "移动站",
    type: "mobile",
    domain: "m.example.com",
    subDomains: [],
    sslEnabled: true,
    status: "maintenance",
    description: "移动端优化站点",
    roles: ["content_admin", "editor"],
    createTime: "2023-04-05T11:30:00",
    updateTime: "2023-06-18T09:25:00",
    totalVisits: 67890,
    todayVisits: 0,
    yesterdayVisits: 560,
    avgResponseTime: 200,
    cpuUsage: 25,
    memoryUsage: 40,
    bandwidthUsage: 15,
  },
]);

// 响应式数据
const sites = ref([...initialSites.value]);
const loading = ref(false);
const searchKeyword = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const dialogVisible = ref(false);
const dialogTitle = ref("新增站点");
const dialogType = ref("add");
const detailVisible = ref(false);
const newSubDomain = ref("");
const currentSite = ref({});

// 表单数据
const siteForm = reactive({
  id: null,
  name: "",
  type: "",
  domain: "",
  subDomains: [],
  sslEnabled: false,
  status: "online",
  description: "",
  roles: [],
});

// 表单验证规则
const siteRules = reactive({
  name: [{ required: true, message: "请输入站点名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择站点类型", trigger: "change" }],
  domain: [
    { required: true, message: "请输入主域名", trigger: "blur" },
    {
      pattern: /^([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}$/,
      message: "请输入有效的域名",
      trigger: "blur",
    },
  ],
});

// 计算属性
const totalSites = computed(() => sites.value.length);
const filteredSites = computed(() => {
  let result = [...sites.value];
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    result = result.filter(
        (site) =>
            site.name.toLowerCase().includes(keyword) ||
            site.domain.toLowerCase().includes(keyword) ||
            site.subDomains.some((sub) => sub.toLowerCase().includes(keyword))
    );
  }
  return result.slice(
      (currentPage.value - 1) * pageSize.value,
      currentPage.value * pageSize.value
  );
});

// 方法
const getSiteTypeName = (type) => {
  const found = siteTypes.find((t) => t.value === type);
  return found ? found.label : "未知类型";
};

const formatDate = (dateString) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  return date.toLocaleString();
};

const getResponseTimePercentage = (time) => {
  // 假设300ms是最大响应时间
  return Math.min(100, Math.max(0, 100 - (time / 300) * 100));
};

const getResponseTimeColor = (time) => {
  if (time < 100) return "#67C23A";
  if (time < 200) return "#E6A23C";
  return "#F56C6C";
};

const getUsageColor = (usage) => {
  if (usage < 50) return "#67C23A";
  if (usage < 80) return "#E6A23C";
  return "#F56C6C";
};

const getAssignedRoles = (roleKeys) => {
  return allRoles.value.filter((role) => roleKeys.includes(role.key));
};

const addSubDomain = () => {
  if (newSubDomain.value.trim() && !siteForm.subDomains.includes(newSubDomain.value)) {
    siteForm.subDomains.push(newSubDomain.value.trim());
    newSubDomain.value = "";
  }
};

const removeSubDomain = (index) => {
  siteForm.subDomains.splice(index, 1);
};

const addSite = (type, row = null) => {
  dialogType.value = type;
  if (type === "add") {
    dialogTitle.value = "新增站点";
    resetForm();
  } else {
    dialogTitle.value = "编辑站点";
    Object.assign(siteForm, JSON.parse(JSON.stringify(row)));
  }
  dialogVisible.value = true;
};

const submitSiteForm = () => {
  // 这里应该有表单验证逻辑
  if (dialogType.value === "add") {
    // 新增站点
    const newSite = {
      ...siteForm,
      id: Math.max(...sites.value.map((s) => s.id)) + 1,
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString(),
      totalVisits: 0,
      todayVisits: 0,
      yesterdayVisits: 0,
      avgResponseTime: 100 + Math.floor(Math.random() * 100),
      cpuUsage: 20 + Math.floor(Math.random() * 50),
      memoryUsage: 30 + Math.floor(Math.random() * 50),
      bandwidthUsage: 10 + Math.floor(Math.random() * 30),
    };
    sites.value.push(newSite);
    ElMessage.success("站点添加成功");
  } else {
    // 编辑站点
    const index = sites.value.findIndex((s) => s.id === siteForm.id);
    if (index !== -1) {
      sites.value[index] = {
        ...sites.value[index],
        ...siteForm,
        updateTime: new Date().toISOString(),
      };
      ElMessage.success("站点更新成功");
    }
  }
  dialogVisible.value = false;
};

const deleteSite = (row) => {
  ElMessageBox.confirm(`确定删除站点 "${row.name}" 吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    sites.value = sites.value.filter((s) => s.id !== row.id);
    ElMessage.success("站点删除成功");
  });
};

const showDetail = (row) => {
  currentSite.value = { ...row };
  detailVisible.value = true;
};

const resetForm = () => {
  siteForm.id = null;
  siteForm.name = "";
  siteForm.type = "";
  siteForm.domain = "";
  siteForm.subDomains = [];
  siteForm.sslEnabled = false;
  siteForm.status = "online";
  siteForm.description = "";
  siteForm.roles = [];
};

const refreshData = () => {
  loading.value = true;
  // 模拟数据刷新
  setTimeout(() => {
    sites.value.forEach((site) => {
      // 随机更新一些统计数据
      site.todayVisits += Math.floor(Math.random() * 50);
      site.avgResponseTime = 100 + Math.floor(Math.random() * 100);
      site.cpuUsage = 20 + Math.floor(Math.random() * 50);
      site.memoryUsage = 30 + Math.floor(Math.random() * 50);
      site.bandwidthUsage = 10 + Math.floor(Math.random() * 30);
    });
    loading.value = false;
    ElMessage.success("数据已刷新");
  }, 800);
};

const handleSearch = () => {
  currentPage.value = 1;
};

const handleSearchClear = () => {
  searchKeyword.value = "";
  currentPage.value = 1;
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

const handlePageChange = (val) => {
  currentPage.value = val;
};

// 初始化
onMounted(() => {
  // 可以在这里添加初始化逻辑
});
</script>

<style scoped>
.site-management {
  padding: 20px;
}

.operation-area {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.pagination-area {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.stats-container {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.performance-charts {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.chart-container {
  width: 30%;
}

.chart-title {
  margin-bottom: 10px;
  font-weight: bold;
}

:deep(.el-descriptions__body) {
  background-color: #f5f7fa;
}

:deep(.el-descriptions__label) {
  width: 120px;
}
</style>
